// App Root
var appPath = getAppPath();

// 是否延迟加载
var lazy = false;

// Datagrid ID
var datagrid_id = "#pageStyleGrid";

// Datagrid URL参数
var datagrid_url = appPath+'/cms/pageStyle_list.do';

// Dialog ID
var dialog_id = "#addPageStyleDlg";

// Form ID
var form_id = "#addPageStyleForm";

/**
 * jQuery加载事件
 */
$(function(){
	// 初始化Datagrid
	initPlugin();
	
	$("#pageId").combobox({url:appPath+'/cms/page_listCombo.do',valueField:'pageId',textField:'pageName'});
});

/**
 * 控件初始化方法
 */
function initPlugin() {
	$(datagrid_id).datagrid({
		url: lazy? '' : datagrid_url,
		height: "full",
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'pageStyleCd',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'cm',title:'操作',width:60,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  //var dataStr = JSON.stringify(rowData); // 最好注释掉此行代码
		    		  var result = "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    		  result += "&nbsp;&nbsp;"
		    		  result += "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/reset-pass.png' title='设为使用' onClick='resetStatus("+rowIndex+")'/></a>";
		    		  result += "&nbsp;&nbsp;"
		    			  result += "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/sum.png' title='数据关联' onClick='linkedData("+rowIndex+")'/></a>";
		    		  return result;
		    	  }
		      }
		]],
		columns:[[
		      {field:'pageStyleCd',title:'模板代码',width:120,align:'center'},
		      {field:'pageStyleName',title:'模板名称',width:180,align:'center'},
		      {field:"pageName",title:'归属页面',width:180,align:'center'},
		      {field:'usedFlgName',title:'状态',width:100,align:'center'},
		      {field:'remark',title:'备注',width:300,align:'left'}
		 ]],
		 pagination:true,
		 rownumbers:true,
		 onLoadSuccess: function() {
			 uncheckAll(this);
			 changeTipInfo("tommy-cell");
		 },
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					deleteData();
				}
			}]
	});
	if (lazy)
		$(datagrid_id).datagrid('options').url = datagrid_url;
}

/**
 * 控件展现方法
 */
function showPlugin() {
	if (lazy) {
		initPlugin();
		lazy = false;
	}		
}

/**
 * 重置模板状态
 */
function resetStatus(rowIndex) {
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	$.loading(true);
	$.ajax({
		url:appPath+'/cms/pageStyle_reset.do',
		data:{pageStyleCd:rowData.pageStyleCd, pageId:rowData.pageId},
		success:function(data){
			$.loading(false);
			if(data!='ok'){
				$.messager.alert('提示信息','模板设置为使用状态失败！','info');
			}else{
				doReload('update');
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，请求失败，'+textStatus,'error');
		}
	});	
}

/**
 * 数据关联
 */
function linkedData(rowIndex) {
	$.loading(true);
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	window.location.replace(appPath + "/jsp/cms/staticManage.jsp?pageStyleCd=" + rowData.pageStyleCd);
}

/**
 * 展现编辑模板
 * @param rowIndex
 */
function showEdit(rowIndex){
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	
	$(form_id).form('clear');
	$("#submitType").val("update");
	
	$(dialog_id).window({
		title:'编辑模板',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		resizable: false,
		collapsible:false,
		minimizable:false,
		maximizable:true
	});
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
	
	$.loading(true);
	$.ajax({
		url:appPath+'/cms/pageStyle_single.do',
		data:{pageStyleCd:rowData["pageStyleCd"]},
		success:function(data){
			rowData = data;
			rowData.ftlContentHtml = rowData.ftlContent;
			$(form_id).form('load',rowData);
			$.loading(false);
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，数据获取未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	$("#pageStyleName").val($.trim($("#pageStyleName").val()));
	
	if(!$(form_id).form('validate')){
		return ;
	}
	
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	var subData = $(form_id);  
    var pagestyleinfo = subData.serialize();    
    
    $.loading(true);
    
    $.ajax({
		url:appPath+'/cms/pageStyle_'+type + '.do',
		type:"post",
		data:pagestyleinfo,
		success:function(data){
			$.loading(false);
			if(data == "error"){
				$.messager.alert('提示信息','该模板名称已存在，请更换其它！','info');
			}else{
				doReload(type);
				closeWindow();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，请求失败，'+textStatus,'error');
		}
	});
}

/**
 * 删除数据
 */
function deleteData() {
	var selections = $(datagrid_id).datagrid('getSelections');
	if(selections == null || selections == ''){
		$.messager.alert('提示信息','请选择要删除的数据','info');
		return ;
	}else{
		$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
			if(r){
				var ids = '';
				for(var i=0;i<selections.length;i++){
					ids += selections[i].pageStyleCd+',';
				}
				ids = ids.substring(0,ids.lastIndexOf(','));
				
				$.loading(true);
				$.ajax({
					url:appPath+'/cms/pageStyle_delMulti.do',
					data:{multi_id:ids},
					success:function(data){
						$.loading(false);
						if(data!='ok'){
							$.messager.alert('提示信息','模板有相关联的模块信息，不能删除！','info');
						}else{
							doReload('delete');
						}
					},
					error:function(XMLHttpRequest, textStatus, errorThrown){
						$.loading(false);
						$.messager.alert('提示信息','抱歉，请求失败，'+textStatus,'error');
					}
				});		
			}
		});
	}
}

/**
 * 预览模板代码
 */
function previewCode() {
   var winHTML = '<html><head><title>模板代码预览</title>';
   winHTML += '<script type="text/javascript" src="'+appPath+'/js/lib/SyntaxHighlighter/scripts/shCore.js"></script>';
   winHTML += '<script type="text/javascript" src="'+appPath+'/js/lib/SyntaxHighlighter/scripts/shBrushXml.js"></script>';
   winHTML += '<link type="text/css" rel="stylesheet" href="'+appPath+'/js/lib/SyntaxHighlighter/styles/shCoreDefault.css"/>';
   winHTML += '<script type="text/javascript">SyntaxHighlighter.all();</script>';
   winHTML += '</head><body><pre class="brush: xhtml">';
   winHTML += $("#ftlContent").val().replace(/\</g, "&lt;");
   winHTML += '</pre></body></html>';
   
   writeMsgToBlank(winHTML);
}

/**
 * 关闭对话框
 */
function closeWindow(){
	$(dialog_id).window('close');
}

/**
 * 展现增加模板
 */
function showAdd(){
	$(form_id).form('clear');
	$("#submitType").val("save");
	$(dialog_id).window({
		title:'增加模板',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		resizable: false,
		collapsible:false,
		minimizable:false,
		maximizable:true
	});
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');	
}

/**
 * 获取请求参数
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	submitObject.pageStyleName = $.trim($('#queryPageStyleName').val());
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	showPlugin();
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $(datagrid_id).datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$(datagrid_id).datagrid('getPager').pagination({pageNumber:pn});
		$(datagrid_id).datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($(datagrid_id).datagrid('getRows').length == $(datagrid_id).datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$(datagrid_id).datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$(datagrid_id).datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('reload');
}
